<?php

error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('America/New_York');
ini_set('display_errors', 1);
set_time_limit(60*30);

require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';
require_once dirname(__FILE__). '/util/TimeUtil.php';

$g_start = microtime(true);

$dbconn = Connection::getInstance();

//$argv[1] = '2011-11';

if(count($argv) ==  2) {
	list($year, $month) = explode('_', date('Y_m', strtotime($argv[1])));
} else {
	list($year, $month) = explode('_', date('Y_m'));
}

/*
$year = '2011';
$month = '11';
$time = '2011_11';
*/

$result = collectUserPlay($year, $month);

echo formatVarianceResult($result, $year, $month);



function collectUserPlay($year, $month) {
	chdir(RAW_DATA_ROOT . '/' . $year . '_' . $month);
	
	$usersPlay = array();
	$variancePerWeek = array();
	
	foreach (glob("*_*") as $filename) {
		
		if (count(explode('_', $filename)) == 2) {
			list($day, $hour) = explode('_', $filename);
			$week = date('W', strtotime($year . $month . $day));
			
			$handler = fopen(RAW_DATA_ROOT . '/' . $year . '_' . $month . '/' . $filename, 'r');
			if ($handler) {
				while (!feof($handler)) {
					$line = fgets($handler);
					if (!empty($line)) {
						$args = explode(':', $line);
						if (!empty($args[4]) && !empty($args[0]) && !empty($args[3]) && !empty($args[11])) {
							$event = $args[4];
							$uid = $args[3];
							$site = $args[11];
							
							if ($event == 'played' && $uid != 0) {
								if (isset($usersPlay[$week][$site][$uid])) {
									$usersPlay[$week][$site][$uid] += 1;
								} else {
									$usersPlay[$week][$site][$uid] = 1;
								}
							}
							
						}
					}
				}
				fclose($handler);
			}
		}
		
		// When it start iterating another week , calculate last week's variance
		if (count($usersPlay) > 1) {
			$lastWeek = $week - 1;
			foreach ($usersPlay[$lastWeek] as $site => $usersPlayFilterBySite) {
				$variancePerWeek[$site][$lastWeek] = getVariance(array_values($usersPlayFilterBySite));
				unset($usersPlay[$lastWeek][$site]);
			}			
		}
	}
	
	// calculate the variance of the last week of this month
	foreach ($usersPlay[$week] as $site => $usersPlayFilterBySite) {
		$variancePerWeek[$site][$week] = getVariance(array_values($usersPlayFilterBySite));
		unset($usersPlay[$week][$site]);
	}
	
	return $variancePerWeek;
}


function getVariance(array $rawdata) {
		$totalNums = count($rawdata);
		$total = 0;
		foreach ($rawdata as $data) {
			$total += $data;
		}
		$avarage = $total / $totalNums;
		
		$varianceTotal = 0;
		foreach ($rawdata as $data) {
			$varianceTotal += pow(($data - $avarage), 2);
		}
		//echo $varianceTotal . ' -----  ' . $totalNums . '<br/>';
		return sprintf("%d", ($varianceTotal / $totalNums));
}

function formatVarianceResult(array $result, $year, $month) {
	$monthStart = date('Y-m-d', mktime(0, 0 , 0, $month, 1, $year));
	$monthEnd = date('Y-m-d', (mktime(0, 0 , 0, ($month + 1), 1, $year) - 100));
	$return = "Variance of User Play:\t$year-$month\n";
	
	foreach ($result as $site => $resultBySite) {
		$return .= "\n\n";
		$return .= $site . ":\n";
		$return .= "Start of Week\tEnd of Week\tVariance of User Play\n";
		foreach ($resultBySite as $week => $weekResult) {
			$weekRange = TimeUtil::getStartAndEndDate($week, $year);
			if ($weekRange['start'] < $monthStart) {
				$weekRange['start'] = $monthStart;
			}
			if ($weekRange['end'] > $monthEnd) {
				$weekRange['end'] = $monthEnd;
			}
			$return .= $weekRange['start'] . '  ---  ' . $weekRange['end'] . "\t" . $weekResult . "\n";
		}
	}
	return $return;
}


